namespace DotNetNuke.UI.WebControls
{

    
    using System;
    using System.IO;
    using System.Net;

    public class CountryLookup
    {
        private static long CountryBegin = 0xffff00L;
        private static string[] CountryCode = new string[] { 
            "--", "AP", "EU", "AD", "AE", "AF", "AG", "AI", "AL", "AM", "AN", "AO", "AQ", "AR", "AS", "AT", 
            "AU", "AW", "AZ", "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BM", "BN", "BO", "BR", 
            "BS", "BT", "BV", "BW", "BY", "BZ", "CA", "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", 
            "CN", "CO", "CR", "CU", "CV", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE", 
            "EG", "EH", "ER", "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "FX", "GA", "GB", "GD", "GE", 
            "GF", "GH", "GI", "GL", "GM", "GN", "GP", "GQ", "GR", "GS", "GT", "GU", "GW", "GY", "HK", "HM", 
            "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IN", "IO", "IQ", "IR", "IS", "IT", "JM", "JO", "JP", 
            "KE", "KG", "KH", "KI", "KM", "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC", "LI", "LK", 
            "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC", "MD", "MG", "MH", "MK", "ML", "MM", "MN", "MO", 
            "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NC", "NE", "NF", "NG", 
            "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "PA", "PE", "PF", "PG", "PH", "PK", "PL", "PM", 
            "PN", "PR", "PS", "PT", "PW", "PY", "QA", "RE", "RO", "RU", "RW", "SA", "SB", "SC", "SD", "SE", 
            "SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SR", "ST", "SV", "SY", "SZ", "TC", "TD", 
            "TF", "TG", "TH", "TJ", "TK", "TM", "TN", "TO", "TP", "TR", "TT", "TV", "TW", "TZ", "UA", "UG", 
            "UM", "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI", "VN", "VU", "WF", "WS", "YE", "YT", "YU", 
            "ZA", "ZM", "ZR", "ZW", "A1", "A2"
         };
        private static string[] CountryName = new string[] { 
            "N/A", "Asia/Pacific Region", "Europe", "Andorra", "United Arab Emirates", "Afghanistan", "Antigua and Barbuda", "Anguilla", "Albania", "Armenia", "Netherlands Antilles", "Angola", "Antarctica", "Argentina", "American Samoa", "Austria", 
            "Australia", "Aruba", "Azerbaijan", "Bosnia and Herzegovina", "Barbados", "Bangladesh", "Belgium", "Burkina Faso", "Bulgaria", "Bahrain", "Burundi", "Benin", "Bermuda", "Brunei Darussalam", "Bolivia", "Brazil", 
            "Bahamas", "Bhutan", "Bouvet Island", "Botswana", "Belarus", "Belize", "Canada", "Cocos (Keeling) Islands", "Congo, The Democratic Republic of the", "Central African Republic", "Congo", "Switzerland", "Cote D'Ivoire", "Cook Islands", "Chile", "Cameroon", 
            "China", "Colombia", "Costa Rica", "Cuba", "Cape Verde", "Christmas Island", "Cyprus", "Czech Republic", "Germany", "Djibouti", "Denmark", "Dominica", "Dominican Republic", "Algeria", "Ecuador", "Estonia", 
            "Egypt", "Western Sahara", "Eritrea", "Spain", "Ethiopia", "Finland", "Fiji", "Falkland Islands (Malvinas)", "Micronesia, Federated States of", "Faroe Islands", "France", "France, Metropolitan", "Gabon", "United Kingdom", "Grenada", "Georgia", 
            "French Guiana", "Ghana", "Gibraltar", "Greenland", "Gambia", "Guinea", "Guadeloupe", "Equatorial Guinea", "Greece", "South Georgia and the South Sandwich Islands", "Guatemala", "Guam", "Guinea-Bissau", "Guyana", "Hong Kong", "Heard Island and McDonald Islands", 
            "Honduras", "Croatia", "Haiti", "Hungary", "Indonesia", "Ireland", "Israel", "India", "British Indian Ocean Territory", "Iraq", "Iran, Islamic Republic of", "Iceland", "Italy", "Jamaica", "Jordan", "Japan", 
            "Kenya", "Kyrgyzstan", "Cambodia", "Kiribati", "Comoros", "Saint Kitts and Nevis", "Korea, Democratic People's Republic of", "Korea, Republic of", "Kuwait", "Cayman Islands", "Kazakstan", "Lao People's Democratic Republic", "Lebanon", "Saint Lucia", "Liechtenstein", "Sri Lanka", 
            "Liberia", "Lesotho", "Lithuania", "Luxembourg", "Latvia", "Libyan Arab Jamahiriya", "Morocco", "Monaco", "Moldova, Republic of", "Madagascar", "Marshall Islands", "Macedonia, the Former Yugoslav Republic of", "Mali", "Myanmar", "Mongolia", "Macau", 
            "Northern Mariana Islands", "Martinique", "Mauritania", "Montserrat", "Malta", "Mauritius", "Maldives", "Malawi", "Mexico", "Malaysia", "Mozambique", "Namibia", "New Caledonia", "Niger", "Norfolk Island", "Nigeria", 
            "Nicaragua", "Netherlands", "Norway", "Nepal", "Nauru", "Niue", "New Zealand", "Oman", "Panama", "Peru", "French Polynesia", "Papua New Guinea", "Philippines", "Pakistan", "Poland", "Saint Pierre and Miquelon", 
            "Pitcairn", "Puerto Rico", "Palestinian Territory, Occupied", "Portugal", "Palau", "Paraguay", "Qatar", "Reunion", "Romania", "Russian Federation", "Rwanda", "Saudi Arabia", "Solomon Islands", "Seychelles", "Sudan", "Sweden", 
            "Singapore", "Saint Helena", "Slovenia", "Svalbard and Jan Mayen", "Slovakia", "Sierra Leone", "San Marino", "Senegal", "Somalia", "Suriname", "Sao Tome and Principe", "El Salvador", "Syrian Arab Republic", "Swaziland", "Turks and Caicos Islands", "Chad", 
            "French Southern Territories", "Togo", "Thailand", "Tajikistan", "Tokelau", "Turkmenistan", "Tunisia", "Tonga", "East Timor", "Turkey", "Trinidad and Tobago", "Tuvalu", "Taiwan, Province of China", "Tanzania, United Republic of", "Ukraine", "Uganda", 
            "United States Minor Outlying Islands", "United States", "Uruguay", "Uzbekistan", "Holy See (Vatican City State)", "Saint Vincent and the Grenadines", "Venezuela", "Virgin Islands, British", "Virgin Islands, U.S.", "Vietnam", "Vanuatu", "Wallis and Futuna", "Samoa", "Yemen", "Mayotte", "Yugoslavia", 
            "South Africa", "Zambia", "Zaire", "Zimbabwe", "Anonymous Proxy", "Satellite Provider"
         };
        public MemoryStream m_MemoryStream;

        public CountryLookup(MemoryStream ms)
        {
            this.m_MemoryStream = ms;
        }

        public CountryLookup(string FileLocation)
        {
            FileStream _FileStream = new FileStream(FileLocation, FileMode.Open, FileAccess.Read);
            this.m_MemoryStream = new MemoryStream();
            byte[] _Byte = new byte[0x101];
            while (_FileStream.Read(_Byte, 0, _Byte.Length) != 0)
            {
                this.m_MemoryStream.Write(_Byte, 0, _Byte.Length);
            }
            _FileStream.Close();
        }

        private long ConvertIPAddressToNumber(IPAddress _IPAddress)
        {
            //string[] _Address = Strings.Split(_IPAddress.ToString(), ".", -1, CompareMethod.Binary);
            string[] _Address = _IPAddress.ToString().Split(".".ToCharArray());
            //if (Information.UBound(_Address, 1) == 3)
            if (_Address.GetUpperBound(1) == 3)
            {
                return (long) Math.Round((double) ((((16777216.0 * Convert.ToDouble(_Address[0])) + (65536.0 * Convert.ToDouble(_Address[1]))) + (256.0 * Convert.ToDouble(_Address[2]))) + Convert.ToDouble(_Address[3])));
            }            
            return 0L;
        }

        private string ConvertIPNumberToAddress(long _IPNumber)
        {
            string _IPNumberPart1 = Convert.ToString((double) ((int)((double) (((double) _IPNumber) / 16777216.0)) % 256.0));
            string _IPNumberPart2 = Convert.ToString((double) ((int)((double) (((double) _IPNumber) / 65536.0)) % 256.0));
            string _IPNumberPart3 = Convert.ToString((double) ((int)((double) (((double) _IPNumber) / 256.0)) % 256.0));
            string _IPNumberPart4 = Convert.ToString((long) ((int)(_IPNumber) % 0x100L));
            return (_IPNumberPart1 + "." + _IPNumberPart2 + "." + _IPNumberPart3 + "." + _IPNumberPart4);
        }

        public static MemoryStream FileToMemory(string FileLocation)
        {
            MemoryStream _MemStream = new MemoryStream();
            byte[] _Byte = new byte[0x101];
            try
            {
                FileStream _FileStream = new FileStream(FileLocation, FileMode.Open, FileAccess.Read);
                while (_FileStream.Read(_Byte, 0, _Byte.Length) != 0)
                {
                    _MemStream.Write(_Byte, 0, _Byte.Length);
                }
                _FileStream.Close();
            }
            catch (FileNotFoundException)
            {
            }
            return _MemStream;
        }

        public string LookupCountryCode(IPAddress _IPAddress)
        {
            int offset=0;
            short depth=0x1f;
            long ipNum=this.ConvertIPAddressToNumber(_IPAddress);
            return CountryCode[this.SeekCountry(ref offset, ref ipNum, ref depth)];
        }

        public string LookupCountryCode(string _IPAddress)
        {
            IPAddress _Address;
            try
            {
                _Address = IPAddress.Parse(_IPAddress);
            }
            catch (FormatException)
            {
                return "--";                
            }
            return this.LookupCountryCode(_Address);
        }

        public string LookupCountryName(IPAddress addr)
        {
            int offset=0;
            short depth=0x1f;
            long ipNum=this.ConvertIPAddressToNumber(addr);
            return CountryName[this.SeekCountry(ref offset, ref ipNum, ref depth)];
        }

        public string LookupCountryName(string _IPAddress)
        {
            IPAddress _Address;
            try
            {
                _Address = IPAddress.Parse(_IPAddress);
            }
            catch (FormatException exception1)
            {
                
                FormatException e = exception1;
                string LookupCountryName = "N/A";
                
                return LookupCountryName;
                
            }
            return this.LookupCountryName(_Address);
        }

        public int SeekCountry(ref int Offset, ref long Ipnum, ref short Depth)
        {
            int SeekCountry=0;
            try
            {
                short refShortHelperS0;
                short endLoopShortHelperS0;
                byte[] Buffer = new byte[7];
                int[] X = new int[3];
                if (Depth == 0)
                {
                    throw new Exception();
                }
                this.m_MemoryStream.Seek((long) (6 * Offset), SeekOrigin.Begin);
                this.m_MemoryStream.Read(Buffer, 0, 6);
                short I = 0;
                do
                {
                    X[I] = 0;
                    short J = 0;
                    do
                    {
                        byte Y = Buffer[(I * 3) + J];
                        if (Y < 0)
                        {
                            Y = (byte) (Y + 0x100);
                        }
                        X[I] += (int) this.vbShiftLeft((long) Y, J * 8);
                        J = (short) (J + 1);
                        endLoopShortHelperS0 = 2;
                    }
                    while (J <= endLoopShortHelperS0);
                    I = (short) (I + 1);
                    endLoopShortHelperS0 = 1;
                }
                while (I <= endLoopShortHelperS0);
                if ((Ipnum & this.vbShiftLeft(1L, Depth)) > 0L)
                {
                    if (X[1] >= CountryBegin)
                    {
                        return (X[1] - ((int) CountryBegin));
                    }
                    refShortHelperS0 = (short) (Depth - 1);
                    return this.SeekCountry(ref X[1], ref Ipnum, ref refShortHelperS0);
                }
                if (X[0] >= CountryBegin)
                {
                    return (X[0] - ((int) CountryBegin));
                }
                refShortHelperS0 = (short) (Depth - 1);
                SeekCountry = this.SeekCountry(ref X[0], ref Ipnum, ref refShortHelperS0);
            }
            catch (Exception)
            {
                
                
               
            }
            return SeekCountry;
        }

        private long vbShiftLeft(long Value, int Count)
        {
            long vbShiftLeft = Value;
            int refIntHelperL0 = Count;
            for (int _Iterator = 1; _Iterator <= refIntHelperL0; _Iterator++)
            {
                vbShiftLeft *= 2L;
            }
            return vbShiftLeft;
        }

        private long vbShiftRight(long Value, int Count)
        {
            long vbShiftRight = Value;
            int refIntHelperL0 = Count;
            for (int _Iterator = 1; _Iterator <= refIntHelperL0; _Iterator++)
            {
                vbShiftRight /= 2L;
            }
            return vbShiftRight;
        }
    }
}

